package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录过滤器
 */
@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1. 放行应该直接放行的资源
        String requestPath =  request.getRequestURI();
        log.info("登录过滤器，拦截当前请求：{}",requestPath);

        String[] pathes = {  //定义直接放行的资源路径
                "/employee/login",
                "/backend"
        };

        for (String pathe : pathes) {
            if(requestPath.startsWith(pathe)){
                //直接放行
                filterChain.doFilter(request,response);
                return ;
            }
        }

        //2. 判断用户是否登录
        HttpSession session = request.getSession();
        Object emp = session.getAttribute("emp");
        if(emp!=null){
            //直接放行
            filterChain.doFilter(request,response);
            return ;
        }

        //3. 不放行资源的访问，告知浏览器当前用户没有资源的访问权限
        String resultJson = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(resultJson);
    }
}
